import json
from decimal import Decimal

from django.db import connection

from app.decorator import jwt_auth
from app.my_exception import MyException
from app.service import wx, ali, payment, order
from libs import payment_lib
from libs.common import error, success, MD5
from libs.form import RawJsonForm

PAY_KEY = 'UGW8CH7NV1E51KEM20'


def refund(request):
    form = RawJsonForm(request.body)
    token = form.get('token')
    order_sn = form.get('order_sn')
    vk = MD5(PAY_KEY + order_sn)
    if token != vk:
        return error()
    pay_fen = form.get_int('pay_fen')
    refund_fen = form.get_int('refund_fen')
    tp_typ = form.get_int('tp_typ')
    refund_no = form.get('refund_no', None)
    desc = form.get('desc')
    resp = {}
    if tp_typ == 1:
        refund_id, tp_resp_obj, _ = wx.WxPay().refund(pay_fen, refund_fen, order_sn, desc, out_refund_no=refund_no)
        resp.update({
            'refund_id': refund_id,
            'tp_resp': tp_resp_obj,
        })
    elif tp_typ == 2:
        refund_id, tp_resp_obj, _ = ali.Ali().refund(refund_fen, order_sn, desc, out_refund_no=refund_no)
        resp.update({
            'refund_id': refund_id,
            'tp_resp': tp_resp_obj,
        })
    else:
        return error('无效的退款方式')
    return success(None, **resp)


@jwt_auth
def pay(request, auth):
    form = RawJsonForm(request.body)
    pay_code = form.get('pay_code')
    order_sn = form.get('order_sn')
    order_typ = form.get_int('order_typ')

    valid_order_typ_arr = [1, 2]
    if order_typ not in valid_order_typ_arr:
        return error('无效的订单类型')
    pay_code_info = payment_lib.get_pay_code_type(pay_code)
    if pay_code_info is None:
        return error('无效的第三方支付方式')
    pay_result = {}
    tp_pay_success = False
    try:
        cashier_id = auth.get('cashier_id')
        with connection.cursor() as cursor:
            if order_typ == 1:  # 购物车支付
                order_pay_data = order.query_third_party_order_pay_data(order_sn, cursor)
                cs_order_id = order_pay_data.get('order_id', 0)
                if cs_order_id == 0:
                    return error('订单不存在')
                pay_log_id = order_pay_data.get('pay_log_id')
                third_party_pay_flag = order_pay_data.get('pay_typ_id')
                pay_amount = order_pay_data.get('pay_amount')
                pay_fen = int(pay_amount * Decimal('100'))
                third_party_pay_data = {'pay_fen': pay_fen, 'order_sn': order_sn}
                pay_result, err = payment.process_cart_payment(cashier_id,
                                                               cs_order_id,
                                                               order_sn,
                                                               pay_log_id,
                                                               third_party_pay_flag,
                                                               pay_code,
                                                               third_party_pay_data)
                if err is not None:
                    raise MyException(err)
                if pay_result == 'SUCCESS':
                    tp_pay_success = True
            elif order_typ == 2:  # 仓储卡充值
                # 判断订单号是否存在
                third_party_pay_flag = pay_code_info.get('code')
                pay_result, err = payment.process_top_up_payment(cashier_id,
                                                                 order_sn,
                                                                 third_party_pay_flag,
                                                                 pay_code)
                if err is not None:
                    raise MyException(err)
                if pay_result == 'SUCCESS':
                    tp_pay_success = True
    except MyException as e:
        if tp_pay_success:
            return success(**pay_result)
        else:
            return error(str(e))
    except Exception as e:
        err = '支付异常'
        print(err, e)
    return error(err)


# 查询订单支付状态
def query_pay_state(request):
    form = RawJsonForm(request.body)
    order_sn = form.get('order_sn')
    order_typ = form.get_int('order_typ')
    jo = {}
    if order_typ == 1:
        with connection.cursor() as cursor:
            order_pay_data = order.query_third_party_order_pay_state(order_sn, cursor)
            if order_pay_data.get('order_id', 0) == 0:
                return error('支付订单不存在')
            order_tp_state = order_pay_data.get('tp_status')
            if order_tp_state != 1:
                tp_order_detail = order_pay_data.get('tp_order_detail')
                if type(tp_order_detail) is str:
                    try:
                        jo = json.loads(tp_order_detail)
                    except Exception:
                        pass
            tp_status = order_pay_data.get('tp_status')
            tp_order_sn = order_pay_data.get('tp_order_sn')
            pay_method = order_pay_data.get('pay_method')
            pay_typ_id = order_pay_data.get('pay_typ_id')
            resp_data = {
                'status': tp_status,
                'tp_order_sn': tp_order_sn,
                'pay_method': pay_method,
                'pay_typ_id': pay_typ_id,
            }
    elif order_typ == 2:
        with connection.cursor() as cursor:
            fields = ['id', 'pay_typ_id', 'tp_status', 'tp_order_sn', 'tp_order_detail']
            pay_data = payment.get_third_party_pay_order(cursor, order_sn, fields)
            if pay_data.get('id', 0) == 0:
                return error('支付订单不存在')
            order_tp_state = pay_data.get('tp_status')
            if order_tp_state != 1:
                tp_order_detail = pay_data.get('tp_order_detail')
                if type(tp_order_detail) is str:
                    try:
                        jo = json.loads(tp_order_detail)
                    except Exception:
                        pass
            tp_status = pay_data.get('tp_status')
            tp_order_sn = pay_data.get('tp_order_sn')
            pay_typ_id = pay_data.get('pay_typ_id')
            resp_data = {
                'status': tp_status,
                'tp_order_sn': tp_order_sn,
                'pay_typ_id': pay_typ_id,
            }
    else:
        return error('无效的订单类型')

    # 统一支付响应字段
    if pay_typ_id == 2:
        ali_resp_trade_status = jo.get('trade_status', '')
        ali_resp_code = jo.get('code', '')
        if ali_resp_trade_status == 'WAIT_BUYER_PAY' or ali_resp_code == '10003':
            jo.update({'trade_state': 'USERPAYING'})
            jo.update({'trade_state_desc': '等待买家付款'})
        else:
            ali_resp_sub_code = jo.get('sub_code', '')
            ali_resp_sub_msg = jo.get('sub_msg', '')
            jo.update({'trade_state': ali_resp_sub_code})
            jo.update({'trade_state_desc': ali_resp_sub_msg})
    resp_data.update(jo)
    return success(resp_data)
